#include "QVideoWidget.h"
#include "Media/Sync/sync.h"
#include "PlayMangent.h"

QVideoWidget::QVideoWidget(QWidget *parent) : QWidget(parent), m_playMangent(nullptr) {
    m_slider = new QSlider(Qt::Horizontal, this);
    m_currentTimeLabel = new QLabel("00:00", this);
    m_slashLabel = new QLabel("/", this);
    m_totalTimeLabel = new QLabel("00:00", this);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    m_videoWidget = new VideoDisplayWidget(this);
    mainLayout->addWidget(m_videoWidget, 3);  // Give video widget a large stretch factor

    QHBoxLayout *controlLayout = new QHBoxLayout();

    controlLayout->addWidget(m_slider, 1);  // Give slider a stretch factor
    controlLayout->addWidget(m_currentTimeLabel);  // Add current time label
    controlLayout->addWidget(m_slashLabel);  // Add slash label
    controlLayout->addWidget(m_totalTimeLabel);  // Add total time label

    mainLayout->addLayout(controlLayout);  // Add control layout to main layout

    connect(m_slider, &QSlider::sliderMoved, this, &QVideoWidget::onSliderMoved);

    setLayout(mainLayout);
}


QVideoWidget::~QVideoWidget() {
}
//set m_totalTimeLabel
void QVideoWidget::setTotalTime(int duration) {
    m_slider->setRange(0, duration);
    m_totalTimeLabel->setText(formatTime(duration));
}

void QVideoWidget::setPlayMangent(PlayMangent *playMangent) {
    if (m_playMangent != playMangent) {
         if (m_playMangent) {
             disconnect(&AVSync::getInstance(), &AVSync::newFrame, this, &QVideoWidget::onNewFrame);
             disconnect(&AVSync::getInstance(), &AVSync::positionChanged, this, &QVideoWidget::onPositionChanged);
         }

        m_playMangent = playMangent;

        if (m_playMangent) {
            connect(&AVSync::getInstance(), &AVSync::newFrame, this, &QVideoWidget::onNewFrame);
            connect(&AVSync::getInstance(), &AVSync::positionChanged, this, &QVideoWidget::onPositionChanged);
        }
    }
}
void QVideoWidget::onSliderMoved(int position)
{
    // 假设PlayMangent有setPosition函数，需要根据实际情况修改
   // m_playMangent->setPosition(position);
}
void QVideoWidget::onPositionChanged(qint64 position)
{
    m_slider->setValue(position/1000);
    auto current_time = formatTime(position/1000 );
    m_currentTimeLabel->setText(current_time);
  //  qDebug() << "current_time:" << current_time <<"- pts:" <<position;
}

QString QVideoWidget::formatTime(qint64 timeInMs)
{
    int hours = timeInMs / 3600;
    int minutes = (timeInMs % 3600) / 60;
    int seconds = timeInMs % 60;

    return QString("%1:%2:%3")
        .arg(hours, 2, 10, QLatin1Char('0'))
        .arg(minutes, 2, 10, QLatin1Char('0'))
        .arg(seconds, 2, 10, QLatin1Char('0'));
}

void QVideoWidget::onNewFrame(const QImage &frame) {
    m_currentFrame = frame;
    m_videoWidget->setFrame(m_currentFrame);
}
